- 請到 https://db-ip.com/db/download/ip-to-country-lite 下載 csv
- 把資料 寫到 ~/App_Data/dbip-country.csv

- 匯入程式參考 IPv4Country.ashx

- 資料庫

CREATE TABLE [dbo].[IPv4Country](
	[IpStart] [bigint] NOT NULL,
	[IpEnd] [bigint] NOT NULL,
	[Country] [char](2) NOT NULL,
	[IPRange] [varchar](50) NULL,
 CONSTRAINT [PK_IPv4Country] PRIMARY KEY CLUSTERED 
(
	[IpStart] ASC,
	[IpEnd] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

// 取得IP所屬國家代碼 (兩碼)
public static string GetCountryByIPv4(string IP)
{
    if (string.IsNullOrEmpty(IP) || IP.Contains(":"))
    {
        return "";
    }
    string[] arrIP = IP.Split('.');

    long ip_number = Convert.ToInt64(Math.Pow(256L, 3L)) * Convert.ToInt64(arrIP[0]) + Convert.ToInt64(Math.Pow(256L, 2L)) * Convert.ToInt64(arrIP[1]) + 256L * Convert.ToInt64(arrIP[2]) + Convert.ToInt64(arrIP[3]);

    var dt = "IPv4Country".SQL().Select().Where("IpStart <=", ip_number).And("IpEnd >=", ip_number).DT(DBC: S3.CST.DBCAdmin);
    if (dt.Rows.Count >= 0)
    {
        return dt.Rows[0]["Country"].ToString();
    }
    else
    {
        return string.Empty;
    }

}